package com.wm.blog_gateway.auth;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wm.blog_common.entity.TAdmin;
import com.wm.blog_gateway.dao.TAdminDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/***
 * @ClassName: AdminDetailsServiceImpl
 * @Description:
 * @Author: wm_yu
 * @Create_time: 18:07 2020-3-30
 */
@Component
public class AdminDetailsServiceImpl implements ReactiveUserDetailsService {


    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private TAdminDAO adminDAO;


    @Override
    public Mono<UserDetails> findByUsername(String username) {
        UserDetailsImpl userDetail = this.getUserDetail(username);
        UserDetails details = new UserDetailsImpl();
        if(!ObjectUtils.isEmpty(userDetail.getId())){
            // 角色集合 todo
            List<GrantedAuthority> authorities = new ArrayList<>();
            details = User.withUsername(username).password(passwordEncoder.encode(userDetail.getPassword())).authorities(authorities).build();
        }
        return Mono.just(details);
    }


    private TAdmin getAdmin(String userName){
        if(StringUtils.isEmpty(userName)){
            return new TAdmin();
        }
        QueryWrapper<TAdmin> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name",userName);
        return Optional.ofNullable(adminDAO.getOne(wrapper)).orElse(new TAdmin());
    }



    public UserDetailsImpl getUserDetail(String username){
        TAdmin admin = this.getAdmin(username);
        UserDetailsImpl  user = new UserDetailsImpl();
        user.setPassword(admin.getPassWord());
        user.setUsername(admin.getUserName());
        user.setId(admin.getId());
        return user;
    }

}
